// token拦截器
import store from "@/store";
import { BASE_URL, ENV } from "./env";
import { log } from 'node:util'
import { useRoute } from 'vue-router'
const route = useRoute()
const tokenInterceptor = (config) => {
  if(config.url === "mlogin") {
    return config;
  }
  // 获取token
  // const token = store.state.user.token;
  // const token = store.getters['user/token'];
  const token = localStorage.getItem("token") || route.query.token;
  const openid = localStorage.getItem("openid") || route.query.openid;
  if (token) {
    config.header = config.header || {};
    config.header["userToken"] = token;
    config.header["openid"] = openid;
  }
  return config;
}
// url拦截器
const urlInterceptor = (config) => {
  // 后续配置到环境变量
  if (config.url.indexOf("http://") === 0 || config.url.indexOf("https://") === 0) {
    return config;
  }
  config.url = BASE_URL[ENV] + config.url;
  return config;
}
// 响应拦截器
export const responseInterceptor = (response) => {
  // 为什么是[1]需要再看看
  let res = response[1];
  // 判断是否正常响应
  if (!res || res.statusCode !== 200) {
    console.log('请求失败', res?.msg || "请检查网络是否畅通")
    return Promise.reject(res);
  }
  const resData = res.data;
  // 判断code
  if (resData.code === 200) {
    return Promise.resolve(resData);
  }
  // 登录过期
  if (resData.code === 401) {
    // 清除token
    localStorage.removeItem("token");
    // store.commit("setToken", null);
    // 跳转到登录页
    // 返回到登陆页面
    return Promise.reject(resData);
  }
  // 其他错误
  console.log(resData.msg || "网络异常")
  return Promise.reject(resData);
}
export const requestInterceptor = (config) => {
  tokenInterceptor(config);
  urlInterceptor(config);
  console.log('请求返回数据：', config)
  return config;
}
